<template>
  <div>
    <div id="geetest-captcha"></div>
    <button class="error" type="button" @click="error" style="width: 0;padding: 0;border: none"></button>
    <button class="success" type="button" @click="success" style="width: 0;padding: 0;border: none"></button>
  </div>
</template>

<script>
export default {
  name: "bind，隐藏按钮式",
  data() {
    return {
      captchaObj: null
    };
  },
  props: ["btn_name"],
  created() {
    // alphaHub.$on("reset_geetest", status => {
    //   this.captchaObj.reset(); // 调用该接口进行重置
    // });
    // this.initGeeest();
  },
  methods: {
    error() {
      this.$emit("error");
    },
    success() {
      this.$emit("success");
    },
    initGeeest() {
      let _this = this;
      let btn_name = this.btn_name;
      let geeTestUrl = this.API.GET_GEE_TEST;
      let handlerEmbed = function(captchaObj) {
        _this.captchaObj = captchaObj;
        let domBtn = document.getElementsByClassName(btn_name)[0];
        domBtn &&
          (domBtn.onclick = function() {
            captchaObj.verify(); // 显示验证码
          });
        _this.captchaObj
          .onReady(() => {
            console.log("geetest on ready");
            /**
             * 为避免出现Geetest组件被重复加载到
             * 将holder加入当前引入Geetest的页面dom后，告知父组件 Geetest组件已经加载完毕。
             * 父组件通过该状态（Geetest组件是否加载完毕）在页面组件beforeRouteLeave时决定是否可以立即返回（前往）其他页面。
             */
            _this.$emit("geetestReady");
          })
          .onSuccess(() => {
            console.log("geetest on success");
            let res = captchaObj.getValidate();
            _this.$emit("success", res);
          })
          .onError(err => {
            localStorage.setItem("Geetest onError", JSON.stringify(err));
            console.log("geetest on error.do reset()");
            _this.$emit("error");
            // _this.captchaObj.reset(); // 调用该接口进行重置
          });
      };
      axios.get(geeTestUrl + "?t=" + new Date().getTime()).then(res => {
        let data = res.data;
        initGeetest(
          {
            gt: data.gt,
            challenge: data.challenge,
            product: "bind", // levan
            offline: !data.success,
            lang: "zh-cn"
          },
          handlerEmbed
        );
      });
    }
  },
  mounted() {
    this.$nextTick(function() {
      alphaHub.$on("reset_geetest", status => {
        this.captchaObj.reset(); // 调用该接口进行重置
      });

      this.initGeeest();
    });
  },
  destroyed() {}
};
</script>

<style lang="sass" rel="stylesheet/sass">
    .hide
        display: none
        .geetest_holder.geetest_wind
            left: 100px

</style>
